﻿using System.Linq;
using EnvDTE;
using Microsoft.VisualStudio.Shell;

namespace Expect.VisualStudio.Extensions.Commands.Handlers
{
    class CreateActorFixtureMethod : ResolvedFixtureCommand
    {
        public CreateActorFixtureMethod(IExpectPackage pkg)
            : base(pkg, CommandIDs.cmdidCreateActorFixtureMethod)
        {
        }

        public override string DisplayText
        {
            get
            {
                return "Fixture class => create actor fixture";
            }
        }

        public override bool ShowCommand(SelectionResolution resolution)
        {
            if (!base.ShowCommand(resolution)) return false;

            if (resolution.FixtureMap == null) return false;
            if (!resolution.FixtureMap.IsActorFixture) return false;
            if (resolution.ClickedRow == null) return false;

            IExpectVSService expectService = (IExpectVSService)GetVSService(typeof(SExpectVSService));
            var codeclass = resolution.FixtureMap.Item.FileCodeModel.CodeElements.GetClass(resolution.FixtureMap.ClassName);
            var methName = resolution.Context.NameProvider.ElementName(resolution.ClickedRow.NamesForFluent().ToArray());
            var args = resolution.ClickedRow.ArgsForFluent().ToArray();
            var item = expectService.GetCurrentItemResolution();
            var provider = item.NameProvider;

            if (codeclass.HasFixtureMethod(provider, methName, args) != null) return false;

            return true;
        }

        public override void ExecuteCommand(SelectionResolution resolution)
        {
            var dte = (EnvDTE80.DTE2)GetVSService(typeof(Microsoft.VisualStudio.Shell.Interop.SDTE));
            var codeclass = resolution.FixtureMap.Item.FileCodeModel.CodeElements.GetClass(resolution.FixtureMap.ClassName);
            var methodName = resolution.Context.NameProvider.ElementName(resolution.ClickedRow.NamesForFluent().ToArray());
            var methodArgs = resolution.ClickedRow.ArgsForFluent().ToArray();

            var method = CreateContainerMethod.GetFixtureMethod(resolution, resolution.ClickedRow, methodName, methodArgs, codeclass);
            var pt = method.GetStartPoint(vsCMPart.vsCMPartBody);

            var wnd = codeclass.ProjectItem.Open();
            wnd.Activate();

            EditorHelper.SetCursorTo(dte, wnd, pt.Line, 0);
        }
    }
}
